// ##登录api##

const query = require("../db/query");
const getNowFormatDate = require("../service/getDate");
const date = require("silly-datetime");
// const loginCheckContorller = require("./loginCheckController");
// const pageController = require("./pageController"); //前台页面路由控制器
// const path = require("path");

// const sessionCheck = require("../controller/sessionCheck"); // session操作模块导入
// var http = require("http");
// var url = require("url");
// var redirect = require("./redirector");
var json = {};
var json1 = {};
var json2 = {};
var json3 = {};
//登录接口

const loginApiContorller = (req, res) => {
  // 获取当前访问用户的uuid
  try {
    function Thistime() {
      //当前日期
      var date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      var mytime = date.toLocaleTimeString(); //获取当前时间
      // myDate.toLocaleString( );
      var time = year + "-" + month + "-" + day + " " + mytime;
      return time;
    }

    // var formatData1 = JSON.stringify(req.query); //json转字符串
    var formatData1 = JSON.stringify(req.body); //json转字符串
    var formatData2 = JSON.parse(formatData1); //字符串转json，
    var uuid1 = req.cookies.uuid || "0";
    var userName = formatData2.username;
    var postPassword = formatData2.password || null;
    remember = formatData2.rememberme || null;
    //   const sqld1 = `SELECT * FROM  user  WHERE  userName ='` + `${userName}` + "'"; //mysql不能又空格
    const sqld1 = `SELECT * FROM  user  WHERE  userName ='` + `${userName}` + "'"; //mysql不能又空格
    query(sqld1).then((data, status, err) => {  //获取用户信息
      json = {};
      // console.log('checkUser', data)
      if (data == "query数据库连接错误0") {
        json.code = 100;
        json.info = data;
        json.status = status;
        json.msg = data;
        json.data = data;
        json.err = err;
        res.json(json);
      } else if (data == null || data == [""] || data == "" || data.length < 1 || data == "null" || data == "[]" || data == []) {
        json.code = 100;
        json.msg = "用户不正确";
        json.status = status;
        json.info = "用户查询失败";
        json.data = data;
        json.err = err;
        res.json(json);
      } else if (data.length > 0) {
        const userStatus = data[0].userStatus || 0;
        const userindate = parseInt(data[0].userIndate || 0);
        var today = parseInt(date.format(new Date(), "YYYYMMDD"));
        // console.log("login:", today, userindate);
        const NowDate = getNowFormatDate.getNowFormatDate();
        const NowDateAdd30 = getNowFormatDate.getNowInUserDateAdd30();
        const getNowDateAddYaer = getNowFormatDate.getNowDateAddYaer();
        if (userStatus == "1") {
          if (today < userindate) { //登录只检查注册有效期是否还在有效期，单次登录有效期最低默认一天，在数据请求接口中单独检查
            //同时判断用户授权是否过期
            json.code = 200;
            json.msg = "用户正确";
            console.log("用户正确", data[0].userName);
            // console.log("查询用户类别成功:", data[0].userType);
            json1 = {
              status,
              err,
            };
            var cname = data[0].cname;
            var OLDpassword = data[0].passWord || null;
            if (postPassword == OLDpassword) {
              json1.msg = "密码验证通过！";
              json.code = 200;
              //   console.log("密码正确", postPassword, OLDpassword);
            //   更新用户注册表中的UUID
            //   const sql0 = `UPDATE user  SET uuid = '` + `${uuid1}` + `'  ,  userIndate = ` + `'${getNowDateAddYaer}' WHERE userName ='` + `${userName}` + "'";
              const sql1 = `UPDATE user  SET uuid ='` + `${uuid1}` + `' WHERE userName ='` + `${userName}` + `'`;
            //   console.log(sql0);
            //   console.log(sql1);
              query(sql1).then((data, status, err) => {
                json2 = {};
                if (data == "query数据库连接错误0") {
                  json.code = 100; //json作为给前端判断的数据，其余json作为不同情况的数据反馈
                  json2.err = err;
                  json2.info = data;
                  json.msg = "更新uuid请求失败！";
                } else {
                  json.code = 200;
                  json2.info = "请求成功！";
                  json2.status = status;
                  json2.msg = "更新UUID请求成功！";
                }
                isShow3 = true;
              });

              // console.log("NowDateAdd30", NowDateAdd30);
              if (remember == "true") {  //勾选记住和不记住登录的处理
                var sql2 = ` replace  INTO onlineuser (uuid,userName,akey,userIndate)VALUES(` + `'${uuid1}'` + "," + `'${userName}'` + "," + `'2022AK13128755602'` + "," + `'${NowDateAdd30}'` + ")";
              json.loginInfo="登录成功，账户记住1个月"
            } else {
                sql2 = `replace INTO onlineuser (uuid,userName,akey,userIndate)VALUES(` + `'${uuid1}'` + "," + `'${userName}'` + "," + `'AK13128755602'` + "," + `'${NowDate}'` + ")";
              }
              query(sql2).then((data, status, err) => {
                json3 = {};
                if (data == "query数据库连接错误0") {
                  json.code = 100;
                  json3.err = err;
                  json3.info = "记录登录状态失败！";
                  json.msg = "请求失败！";
                } else {
                  json3.msg = "请求成功！";
                  json.code = 200;
                  json3.info = "记录登录请求成功！";
                  json3.status = status;
                }
                isShow4 = true;
              });
            } else {
              json.code = 100;
              json1.info = data;
              json1.status = status;
              json.msg = "密码验证失败！";
              // throw new Error("json")
            }
            isShow2 = true; //cname
            var userType = data[0].userType;
            if (json.code == 200) {
              json.cname = cname;
              res.cookie("userName", "", {});
              res.cookie("userName", userName, {
                maxAge: 365 * 24 * 60 * 60 * 1000,
                httpOnly: false,
              });
              res.cookie("userType", "", {});
              res.cookie("userType", userType, {
                maxAge: 365 * 24 * 60 * 60 * 1000,
                httpOnly: false,
              });
              isShow = true;
              json.json1 = json1;
              json.json2 = json2;
              json.json3 = json3;
              
              console.log("登陆成功:", userName, Thistime());
              // console.log("cookies", req.cookies);
              res.json(json);
            } else {
              json.code = 100;
              isShow = true;
              json.json1 = json1;
              json.json2 = json2;
              json.json3 = json3;
              res.json(json);
            }
          } else {
            res.json({
              code: 100,
              msg: "用户过期了！",
              info: status,
              error:"error"
            });
          }
        } else {
          res.json({
            code: 100,
            msg: "用户账户被停用！",
            info: status,
            error:"error"
          });
        }
      } else {
        res.json(json);
        console.log("查询用户错误", data);
      }
    });
  } catch (error) {
    res.json(error);
    console.log("login错误", error);
  } finally {
    // console.log("登陆请求:", userName, Thistime());
    // res.end();
  }
};
module.exports = {
  loginApiContorller,
};
